package com.yiwei.zxp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.activity.BoothPacketActivity;
import com.yiwei.zxp.activity.BussinessMsgTotalActivity;
import com.yiwei.zxp.activity.HomeTypeActivity;
import com.yiwei.zxp.activity.InviteActivity;
import com.yiwei.zxp.activity.LoginNewActivity;
import com.yiwei.zxp.activity.RankActivity;
import com.yiwei.zxp.activity.SearchActivity;
import com.yiwei.zxp.activity.SendEvaluateActivity;
import com.yiwei.zxp.activity.WebViewActivity;
import com.yiwei.zxp.adapter.HomeBottomCateAdapter;
import com.yiwei.zxp.adapter.MallGoodsAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ShopMallListBean;
import com.yiwei.zxp.api.model.ShopIndexModel;
import com.yiwei.zxp.api.model.ShopMallListModel;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.MsgTotalEvent;
import com.yiwei.zxp.util.AppBarStateChangeListener;
import com.yiwei.zxp.util.GlideImageLoader;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.BottomIconText;
import com.yiwei.zxp.view.ObservableScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-5-26.
 */

public class ShopMallFragment extends BaseFragment implements ObservableScrollView.ScrollViewListener {
    @BindView(R.id.index_banner)
    Banner banner;
    @BindView(R.id.btn_menu)
    ImageView btnMenu;
    @BindView(R.id.btn_search)
    SuperButton btnSearch;
    @BindView(R.id.btn_message)
    ImageView btnMessage;
    @BindView(R.id.txt_message_num)
    TextView txtMessageNum;
    @BindView(R.id.btn_tao)
    BottomIconText btnTao;
    @BindView(R.id.btn_rank)
    BottomIconText btnRank;
    @BindView(R.id.btn_invite)
    BottomIconText btnInvite;
    @BindView(R.id.btn_packet)
    BottomIconText btnPacket;
    //    @BindView(R.id.tablayout)
//    TabLayout tablayout;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.main_content)
    CoordinatorLayout mainContent;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.layout_toolbar_top)
    LinearLayout layoutToolbarTop;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.list_cate)
    RecyclerView listCate;
    Unbinder unbinder;
    private MallGoodsAdapter adapter;
    private String cate_id;
    private HomeBottomCateAdapter homeBottomCateAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_shop_mall;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        scrollView.setScrollViewListener(this);
        list.setNestedScrollingEnabled(false);
//        list.addOnScrollListener(onLoadeMoreListener);
        banner.setImageLoader(new GlideImageLoader());
        banner.setIndicatorGravity(BannerConfig.CENTER);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()

        {
            @Override
            public void onRefresh() {
                currentPage = 1;
//                onLoadeMoreListener.setPage(1);
                getIndex();

                if (!UserInfoGlobal.isLogin()) {
                    txtMessageNum.setVisibility(View.GONE);
                } else {
                    ((BussinessMainActivity) getActivity()).getMsgTotal();
                }
//                getShopMallList(1);

            }
        });

        appbar.addOnOffsetChangedListener(new

                                                  AppBarStateChangeListener() {
                                                      @Override
                                                      public void onStateChanged(AppBarLayout appBarLayout, State state) {
                                                          if (state == State.EXPANDED) {

                                                              //展开状态

                                                          } else if (state == State.COLLAPSED) {

                                                              //折叠状态

                                                          } else {

                                                              //中间状态

                                                          }
                                                      }

                                                      @Override
                                                      public void onRefresh(int offset) {
                                                          //初始verticalOffset为0，不能参与计算。
                                                          btnSearch.setShapeSolidColor(changeSearchAlpha(getResources().getColor(R.color.white), Math.abs(offset * 1.0f) / appbar.getTotalScrollRange()));
                                                          btnSearch.setUseShape();
                                                          toolbar.setBackgroundColor(changeAlpha(getResources().getColor(R.color.main_color), Math.abs(offset * 1.0f) / appbar.getTotalScrollRange()));
                                                          if (offset >= 0) {
                                                              refresh.setEnabled(true);
                                                          } else {
                                                              refresh.setEnabled(false);
                                                          }
                                                      }
                                                  });

        adapter = new
                MallGoodsAdapter(getActivity());
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        list.setLayoutManager(layoutManager);
        list.setAdapter(adapter);


        homeBottomCateAdapter = new HomeBottomCateAdapter(getContext());
        homeBottomCateAdapter.setOnChooseListener(new HomeBottomCateAdapter.OnChooseListener() {
            @Override
            public void onClick(String id) {
                cate_id = id;
                getShopMallList(1);
            }
        });
        listCate.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        listCate.setAdapter(homeBottomCateAdapter);
        cate_id = "0";
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgTotalEvent event) {
        if (event.totalCount == 0) {
            if (txtMessageNum != null)
                txtMessageNum.setVisibility(View.GONE);
        } else {
            if (txtMessageNum != null) {
                txtMessageNum.setVisibility(View.VISIBLE);
                txtMessageNum.setText(event.totalCount + "");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getIndex();
    }


//    public void getMsgTotal() {
//        if (!Network.checkNetwork(getContext())) {
//            ToastUtil.show(getContext(), "网络连接失败");
//            return;
//        }
//        Api.api_service.getMessageCenter().compose(RxLifeUtil.checkOn(this)).
//                doFinally(() -> {
//                    try {
//
//                    } catch (NullPointerException e) {
//
//                    }
//                }).
//                subscribe(result -> {
//                    if (result.datas.totalCount == 0) {
//                        txtMessageNum.setVisibility(View.GONE);
//                    } else {
//                        txtMessageNum.setVisibility(View.VISIBLE);
//                        txtMessageNum.setText(result.datas.totalCount + "");
//                    }
//                });
//    }

    public void getIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);

        Api.api_service.getShopIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
//                    isGetData = true;
                    setIndexData(result.datas);
                });
    }

    public void getShopMallList(int page) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        ShopMallListBean bean = new ShopMallListBean();
        bean.page = page;
        bean.cate_id = cate_id;
        Api.api_service.getShopMallList(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                        isOkRefresh = true;
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setShopMallList(page, result.datas);
                });
    }

    private void setShopMallList(int page, List<ShopMallListModel.DatasBean> datas) {
        if (adapter != null) {
            adapter.add(datas, page == 1);
            if (adapter.getItemCount() == 0) {
                if (layoutEmpty != null)
                    layoutEmpty.setVisibility(View.VISIBLE);
            } else {
                if (layoutEmpty != null)
                    layoutEmpty.setVisibility(View.GONE);
            }
        }
    }

    private void setIndexData(ShopIndexModel.DatasBean datas) {
        if (datas.banner != null && datas.banner.size() != 0) {
            List<String> bannerdata = new ArrayList<String>();

            for (int i = 0; i < datas.banner.size(); i++) {
                bannerdata.add(datas.image_host + datas.banner.get(i).image_url);
            }

            banner.setImages(bannerdata).setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (TextUtils.isEmpty(datas.banner.get(position).link)) {
                        return;
                    }
                    banner.setAlpha(0.5f);
                    banner.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            banner.setAlpha(1f);
                            Intent intent = new Intent(getContext(), WebViewActivity.class);
                            intent.putExtra("url", datas.banner.get(position).link);
                            startActivity(intent);
                            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                        }
                    }, 200);


                }
            }).start();
        }


        ShopIndexModel.DatasBean.CatsBean catsBean = new ShopIndexModel.DatasBean.CatsBean();
        catsBean.catname = "全部";
        catsBean.id = "0";
        datas.cats.add(0, catsBean);
//        homeBottomCateAdapter.setPoi(selectCatePoi);
        homeBottomCateAdapter.update(datas.cats);


        getShopMallList(1);
//        Log.i("dasdasdadas", "1111序号：" + selectCatePoi + "id=" + cate_id);
    }

    public int changeSearchAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction + 177);
        if (alpha >= 255) {
            alpha = 255;
        }
        return Color.argb(alpha, red, green, blue);
    }

    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }


    @OnClick({R.id.btn_message, R.id.btn_menu, R.id.btn_search, R.id.btn_tao, R.id.btn_rank, R.id.btn_invite, R.id.btn_packet})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_menu:
                Util.startActivity(getActivity(), HomeTypeActivity.class);
                break;
            case R.id.btn_search:
                Util.startActivity(getActivity(), SearchActivity.class);
                break;
            case R.id.btn_message:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getContext(), LoginNewActivity.class);
                    return;
                }
                Util.startActivity(getActivity(), BussinessMsgTotalActivity.class);
                break;
            case R.id.btn_tao:
                Util.startActivity(getActivity(), SendEvaluateActivity.class);
                ToastUtil.makeText(getContext(), "敬请期待");
                break;
            case R.id.btn_rank:
//                ToastUtil.makeText(getContext(), "敬请期待");
                Util.startActivity(getActivity(), RankActivity.class);
                break;
            case R.id.btn_invite:
//                ToastUtil.makeText(getContext(), "敬请期待");
                Util.startActivity(getActivity(), InviteActivity.class);
                break;
            case R.id.btn_packet:
                Util.startActivity(getActivity(), BoothPacketActivity.class);
                break;
        }
    }

    private boolean isOkRefresh = false;

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
            //底部加载
            if (isOkRefresh) {
                isOkRefresh = false;
                currentPage++;
                getShopMallList(currentPage);
            }
        }

    }

    private int currentPage = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);

        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
//        unbinder.unbind();
    }

}
